package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
)

const josnFilePath = "./users.json"

//很简单
func ReadFile(josnFilePath string) (content []byte) {
	content, err := os.ReadFile(josnFilePath)
	if err != nil {
		panic(err)
	}
	fmt.Println(josnFilePath, "Successfully open File")
	return
}

//result内容很直观
func IoutilReadFile(josnFilePath string) (contents []byte) {
	if contents, err := ioutil.ReadFile(josnFilePath); err == nil {

		//因为contents是[]byte类型，直接转换成string类型后会多一行空格,需要使用strings.Replace替换换行符
		/*result := strings.Replace(string(contents), "\n", "", 1)
		fmt.Println(josnFilePath, "Successfully open File")
		return result*/
		return contents
	} else {
		panic(err)
	}
	return
}

func OsReadAll(josnFilePath string) (contents []byte) {
	if fileObj, err := os.Open(josnFilePath); err == nil {
		defer fileObj.Close()
		if contents, err := ioutil.ReadAll(fileObj); err == nil {
			fmt.Println(josnFilePath, "Successfully open File")
			//result := strings.Replace(string(contents), "\n", "", 1)
			return contents
		} else {
			panic(err)
		}
	}
	return

}

type users struct {
	Users []user `json:"users`
}

type user struct {
	Name   string `json:"name"`
	Type   string `json:"type"`
	Age    uint8  `json:"age"`
	Social struct {
		Facebook string `json:"facebook"`
		Twitter  string `json:"twitter"`
	} `json:"social"`
}

func (u *user) PrintInfo() {
	fmt.Println("User Type: ", u.Type)
	fmt.Println("User Age: ", u.Age)
	fmt.Println("User Name: ", u.Name)
	fmt.Println("Facebook Url: ", u.Social.Facebook)
}

func main() {

	//第1种:
	content := ReadFile(josnFilePath)
	//第2种:
	//content := IoutilReadFile(josnFilePath)
	//第3种:
	//content := OsReadAll(josnFilePath)
	fmt.Println("Content内容", content)

	var users users
	err := json.Unmarshal(content, &users)
	if err != nil {
		panic(err)
	}

	for _, user := range users.Users {
		user.PrintInfo()
	}
	fmt.Println(users)

}
